package TCP;

import com.sun.security.ntlm.Server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ThreadTcp {
    ServerSocket listenSocket=null;

    public ThreadTcp(int port) throws IOException {
        this.listenSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器开启");
        while (true) {
            Socket socket = listenSocket.accept();
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        serverprocess(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }

    private void serverprocess(Socket socket) throws IOException {
        String log1=String.format("[%s:%d]客户端上线!",
                socket.getInetAddress().toString(),
                socket.getPort());
        System.out.println(log1);
        try (InputStream inputStream=socket.getInputStream();
             OutputStream outputStream=socket.getOutputStream()){
            while (true) {
                Scanner scanner=new Scanner(inputStream);
                if(!scanner.hasNext()){
                    String log=String.format("[%s,%d] 客户端下线",socket.getInetAddress().toString(),socket.getPort());
                    System.out.println(log);
                    break;
                }
                String request=scanner.next();
                String response= process(request);
                PrintWriter writer=new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();
                String log=String.format("[%s,%d],req:%s resp:%s",socket.getInetAddress().toString()
                                                                    ,socket.getPort()
                                                                    ,request,response);
                System.out.println(log);
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            socket.close();
        }
    }

    private String process(String str) {
        return str;
    }

    public static void main(String[] args) throws IOException {
        ThreadTcp threadTcp=new ThreadTcp(9090);
        threadTcp.start();
    }
}
